<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		errorModal,
		ignoreHtml,
		getUrl,
		confirmModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		changeConfigAttr,
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
		
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import moment from '@/static/js/moment.js'
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				applyUserIdCacheKey: 'zyk-sld-consumablesApply-applyUserId-cache',
				partakeInstIdCacheKey: 'zyk-sld-consumablesApply-partakeInstId-cache',
				feesAggregatedWayCodeCacheKey: 'zyk-sld-consumablesApply-feesAggregatedWayCode-cache',
				researchDevelopmentIdCacheKey: 'zyk-sld-consumablesApply-researchDevelopmentId-cache',
				businessOpportunityIdCacheKey: 'zyk-sld-consumablesApply-businessOpportunityId-cache',
				saleOrderIdCacheKey: 'zyk-sld-consumablesApply-saleOrderId-cache',
				newProductIdCacheKey: 'zyk-sld-consumablesApply-newProductId-cache',
				fileKey:'130'
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId', 'salaryInstId', 'salaryInstName'])
		},
		methods:{
			onSubChange(editor){
				let _that = this.$refs.autoform
				let that = this
				if(editor.workList.length) {
					_that.formdata.totalAmount = this._.sum(editor.workList.map(e=>ptFloat(e.totalPrice)))
				}
			},
			formSubmit(){
				let _that = this
				_that.formdata.updateBottomFileFlag= true
				if(Object.prototype.toString.call(_that.$refs.autoform.formdata.bottomFileList) == "[object String]"){
					_that.formdata.bottomFileListStr = _that.$refs.autoform.formdata.bottomFileList|| ''
				}else{
					_that.formdata.bottomFileListStr = JSON.stringify(_that.$refs.autoform.formdata.bottomFileList || []) || ''
					
				}
				delete _that.formdata.bottomFileUpload
				delete _that.formdata.bottomFileList
				if(_that.edit){
					_that.om.formSave("consumablesApply/doUpdate",_that.formdata,_that)
				}else{
					_that.om.formSave("consumablesApply/doAdd",_that.formdata,_that)
				}
			},
			initLoad(options){
				let _that = this
				let fileId = options.fileId
				let ajaxArr = [
					{
						url:'inventoryCategory/getExistingProductLineAssortment',
					}]
					if(fileId){
						ajaxArr.push({
							url:"consumablesApply/getValue",
							param:{
								fileId:fileId
							}
						})
					}

				formModelLoad(ajaxArr,function(res,mainData){
					changeEditor("title1","marketingPlanningProductId","data",configSelectData(res[0],'id','name'),mainData)
					changeEditor("title1","applyUserId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify({
								firstUserId: _that.userId
							}),
							url:'temployee/getStaffCombogrid',
							namefield:'userPosInstName',
							initload:true,
							searchfield:'q',
							cachename:_that.applyUserIdCacheKey
						}
					},null,mainData)
					
					_that.om.request(
						'orgInstPosUserOfficial/findInstByUserIdOrPostId',
						{
							userId: _that.userId
						}
					).then(res=>{
						_that.$refs.autoform.changeEditor("title1","applyInstId","data",configSelectData(res,"id","instName"))
					})

					changeEditor("title1","partakeInstId",{
						"link":'../../public/search/search',
						"linkParam":{
							other:JSON.stringify(),
							url:'tinstitution/getComboTree',
							namefield:'text',
							initload:true,
							cachename:_that.partakeInstIdCacheKey
						}
					},null,mainData)
					
					_that.om.request(
						'orgInstPosUserOfficial/getUserListByInstPosId',
						{
							instId: _that.salaryInstId
						},
					).then(res=>{
						_that.$refs.autoform.changeEditor("title1","partakeUserId","data",configSelectData(res,"id","username"))
					})
					
					changeEditor("title1","feesAggregatedWayCode",{
						"linkParam":{
							other:JSON.stringify({
								code: 40346
							}),
							url:"tsysdict/getComboTree",
							cachename:_that.feesAggregatedWayCodeCacheKey,
							initload:true,
							namefield:'text'
						}
					},null,mainData)
					
					changeEditor("title1","researchDevelopmentId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify(),
							url:'createProjectShow/findCreateProjectShowPage',
							namefield:'projectName',
							extrafield:'typeName',
							initload:true,
							searchfield:'q',
							cachename:_that.researchDevelopmentIdCacheKey
						}
					},null,mainData)
					
					changeEditor("title1","businessOpportunityId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify(),
							url:'biddingProject/getBidding',
							namefield:'biddingProjectName',
							extrafield:'biddingCode',
							initload:true,
							searchfield:'q',
							cachename:_that.businessOpportunityIdCacheKey
						}
					},null,mainData)
					
					changeEditor("title1","saleOrderId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify(),
							url:'customerRequirementShow/getHeaderDataToDelivery',
							namefield:'customerRequirementCode',
							notefield:'customerNameX',
							initload:true,
							searchfield:'q',
							cachename:_that.saleOrderIdCacheKey
						}
					},null,mainData)
					
					changeEditor("title1","newProductId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify({
								likeFlag: false
							}),
							url:'productShowSecond/getProductPage',
							namefield:'newProductCode',
							notefield:'newProductName',
							initload:true,
							searchfield:'q',
							cachename:_that.newProductIdCacheKey
						}
					},null,mainData)
					
					if (_that.subEditorObj['title2']) {
						changeEditor("title2", "dataStr", {
							getWorkParam: 'getWorkParam',
							titleTemplate: "  <%= '物品编码：' + substanceCode %>",
							subtitle1Template: "<%= '物品名称：' + substanceName %>",
						}, null, mainData)
					}
					
					let tempFileList = []
					let fileUrlList = []
					changeEditor('bottominfo','bottomFileUpload','fileUploadKey',"130",mainData)
					changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
					changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
					
					if(fileId){
						let fieldArr = getFormFields(mainData)
						fieldArr.push("id")
						for(let index in res[1].value){
							if(fieldArr.includes(index)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[1].value[index])
								_that.$set(_that.formdata,index,res[1].value[index])
							}
						}
						changeEditor("title1","applyUserId",{
							link:'../../public/pageSearch/pageSearch',
							"linkParam":{
								other:JSON.stringify({
									firstUserId: res[1].value.applyUserId
								}),
								url:'temployee/getStaffCombogrid',
								namefield:'userPosInstName',
								initload:true,
								searchfield:'q',
								cachename:_that.applyUserIdCacheKey
							}
						},null,mainData)
						_that.om.request(
							'orgInstPosUserOfficial/findInstByUserIdOrPostId',
							{
								userId: res[1].value.applyUserId
							}
						).then(res=>{
							_that.$refs.autoform.changeEditor("title1","applyInstId","data",configSelectData(res,"id","instName"))
							_that.$refs.autoform.initSelectIndex("title1","applyInstId")
						})
						_that.om.request(
							'orgInstPosUserOfficial/getUserListByInstPosId',
							{
								instId: res[1].value.applyInstId
							},
						).then(res=>{
							_that.$refs.autoform.changeEditor("title1","partakeUserId","data",configSelectData(res,"id","username"))
						})
						if(_that.formdata.feesAggregatedWayCode){
							let idArr = _that.formdata.feesAggregatedWayCode.split(",")
							let nameArr = _that.formdata.feesAggregatedWayName.split(",")
							let feesAggregatedWayList = []
							for(let index in idArr){
								let obj = {
									id:idArr[index],
									text:nameArr[index]
								}
								feesAggregatedWayList.push(obj)
							}
							changeEditor('title1', 'feesAggregatedWayCode', {
								initSelect: feesAggregatedWayList
							},null,mainData)
						}
						if(_that.subEditorObj["title2"]){
							let datalist = res[1].value.dataList
							_that.subEditorObj["title2"].workList = datalist
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataStr",JSON.stringify(datalist))
							_that.$set(_that.formdata,"dataStr",JSON.stringify(datalist))
						}
						if(_that.formdata.bottomFileList){
							let tempFileList = []
							let fileUrlList = _that.formdata.bottomFileList.map(t=>{
								tempFileList.push(t.fileSaveName)
								return t.fileSaveName
							})
							changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
							changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
						}
						_that.$nextTick(function(){
							_that.$refs.autoform.initSelectIndex("title1","marketingPlanningProductId")
						})
					}
					
					_that.$nextTick(function(){
						if(!_that.$refs.autoform.formdata.applyUserId){
							_that.$refs.autoform.formdata.applyUserId = _that.userId
							_that.$refs.autoform.formdata.applyUserName = _that.userName
						}
						if(!_that.$refs.autoform.formdata.applyInstId){
							_that.om.request(
								'orgInstPosUserOfficial/findInstByUserIdOrPostId',
								{
									userId: _that.$refs.autoform.formdata.applyUserId
								}
							).then(res=>{
								_that.$refs.autoform.formdata.applyInstId = _that.salaryInstId
								_that.$refs.autoform.formdata.applyInstName = _that.salaryInstName
								_that.$refs.autoform.changeEditor("title1","applyInstId","data",configSelectData(res,"id","instName"))
								_that.$refs.autoform.initSelectIndex("title1","applyInstId")
							})
						}
						if(!_that.$refs.autoform.formdata.applyDate){
							_that.$refs.autoform.formdata.applyDate = moment().format('YYYY-MM-DD')
						}
						if(!_that.$refs.autoform.formdata.partakeInstId){
							_that.$refs.autoform.formdata.partakeInstId = _that.salaryInstId
							_that.$refs.autoform.formdata.partakeInstName = _that.salaryInstName
						}
						if(!_that.$refs.autoform.formdata.partakeUserId){
							_that.om.request(
								'orgInstPosUserOfficial/getUserListByInstPosId',
								{
									instId: _that.$refs.autoform.formdata.partakeInstId
								},
							).then(res=>{
								_that.$refs.autoform.formdata.partakeUserId = _that.userId
								_that.$refs.autoform.formdata.partakeUserName = _that.userName
								_that.$refs.autoform.changeEditor("title1","partakeUserId","data",configSelectData(res,"id","username"))
								_that.$refs.autoform.initSelectIndex("title1","partakeUserId")
							})
						}
						
					})
				},options)
			},
			clearApplyUserId(){
				let _that = this
				_that.$refs.autoform.clear("title1",'applyUserId')
				_that.$refs.autoform.clear("title1",'applyInstId')
			},
			clearPartakeInstId(){
				let _that = this
				_that.$refs.autoform.clear("title1",'partakeInstId')
				_that.$refs.autoform.clear("title1",'partakeUserId')
				_that.$refs.autoform.changeEditor("title1","partakeUserId","data",configSelectData([],"id","username"))
			},
			clearResearchDevelopmentId(){
				let _that = this
				_that.$refs.autoform.clear("title1",'researchDevelopmentId')
				_that.$refs.autoform.clear("title1",'researchDevelopmentCode')
			},
			clearBusinessOpportunityId(){
				let _that = this
				_that.$refs.autoform.clear("title1",'businessOpportunityId')
				_that.$refs.autoform.clear("title1",'businessOpportunityCode')
			},
			getWorkParam() {
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				return {
					applyUserId:formdata.applyUserId,
					applyUserName:formdata.applyUserName,
					applyInstId:formdata.applyInstId,
					applyInstName:formdata.applyInstName,
				};
			},
		},
		onLoad(options) {
			let _that = this
			_that.initLoad(options)
		},
		onShow() {
			let _that = this
			if(_that.$refs.autoform){
				for (var fieldId in _that.subEditorObj) {
					var editor = _that.subEditorObj[fieldId];
					uni.getStorage({
						key: getWorkCacheKey(fieldId),
						success: function(res) {
							editor.workList = res.data;
							_that.onSubChange(editor)
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					});
				};
				uni.getStorage({
					key:_that.applyUserIdCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.applyUserId = d.id
							formdata.applyUserName = d.username
							_that.$refs.autoform.changeEditor('title1', 'applyUserId', {
								linkParam: {
									other:JSON.stringify({
										firstUserId: d.id
									}),
									url:'temployee/getStaffCombogrid',
									namefield:'userPosInstName',
									initload:true,
									searchfield:'q',
									cachename:_that.applyUserIdCacheKey
								}
							});
							_that.om.request(
								'orgInstPosUserOfficial/findInstByUserIdOrPostId',
								{
									userId: d.id
								}
							).then(res=>{
								formdata.applyInstId = d.salaryPosInstId
								formdata.applyInstName = d.salaryPosInstName
								_that.$refs.autoform.changeEditor("title1","applyInstId","data",configSelectData(res,"id","instName"))
								_that.$refs.autoform.initSelectIndex("title1","applyInstId")
							})
							uni.removeStorage({
								key:_that.applyUserIdCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key: _that.partakeInstIdCacheKey,
					success: function(res) {
						if(res.data){
							let d = res.data
							var formdata  = _that.$refs.autoform.formdata
							if(formdata.partakeInstId != d.id){
								_that.om.request(
									'orgInstPosUserOfficial/getUserListByInstPosId',
									{
										instId: d.id
									},
								).then(res=>{
									_that.$refs.autoform.changeEditor("title1","partakeUserId","data",configSelectData(res,"id","username"))
									_that.$refs.autoform.clear("title1",'partakeUserId')
								})
							}
							
							formdata.partakeInstId = d.id
							formdata.partakeInstName = d.text	

							
							uni.removeStorage({
								key: _that.partakeInstIdCacheKey
							});
						}
					}
				});
				uni.getStorage({
					key:_that.feesAggregatedWayCodeCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.feesAggregatedWayCode = d.map(e=>e.id).join(',')
							formdata.feesAggregatedWayName = d.map(e=>e.text).join(',')
							_that.$refs.autoform.changeEditor('title1', 'feesAggregatedWayCode', {
								initSelect: d
							})
							uni.removeStorage({
								key:_that.feesAggregatedWayCodeCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.researchDevelopmentIdCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.researchDevelopmentId = d.id
							formdata.researchDevelopmentName = d.projectName
							formdata.researchDevelopmentCode = d.projectCode
							uni.removeStorage({
								key:_that.researchDevelopmentIdCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.businessOpportunityIdCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.businessOpportunityId = d.id
							formdata.businessOpportunityName = d.biddingProjectName
							formdata.businessOpportunityCode = d.biddingCode
							uni.removeStorage({
								key:_that.businessOpportunityIdCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.saleOrderIdCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.saleOrderId = d.customerRequirementId
							formdata.saleOrderCode = d.customerRequirementCode
							uni.removeStorage({
								key:_that.saleOrderIdCacheKey
							})
						}
					}
				})
				uni.getStorage({
					key:_that.newProductIdCacheKey,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.newProductId = d.id
							formdata.newProductCode = d.newProductCode
							uni.removeStorage({
								key:_that.newProductIdCacheKey
							})
						}
					}
				})
			}
		}
	}
</script>
<style></style>                                                                                                                                                                                                                                                                                                                  
                                                                                              